<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <#include "../../common/header.ftl">

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.12.1/bootstrap-table.min.css">
    <!-- Latest compiled and minified JavaScript -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.12.1/bootstrap-table.min.js"></script>
    <!-- Latest compiled and minified Locales -->
    <script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.12.1/locale/bootstrap-table-zh-CN.min.js"></script>

    <link rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.5/css/bootstrap-select.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.5/js/bootstrap-select.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.5/js/i18n/defaults-zh_CN.min.js"></script>
</head>
<body class="btn-body">
<div class="container-fluid">
    <#include "../../common/left-nav.ftl">

    <form class="form-horizontal" id="dataForm">
        <div class="main-box">
            <ol class="breadcrumb crumbs always-top">
                <li><a href="${base}/admin/project">项目管理</a></li>
                <li class="active">编辑</li>

                <div class="form-btns">
                    <button type="submit" class="btn btn-primary btn-sm">
                        <span class="glyphicon glyphicon-floppy-disk"></span> 保存
                    </button>

                    <a href="${base}/admin/project" type="button" class="btn btn-danger btn-sm">
                        <span class="glyphicon glyphicon-remove"></span> 取消
                    </a>
                </div>
            </ol>
            <input type="hidden" value="${type!}" name="type">
            <div class="container-fluid">
                <div class="row" style="margin-top: 20px;">
                    <div class="col-md-6">
                        <div class="panel panel-freight">
                            <div class="panel-heading"><b>托运方信息</b></div>
                            <div class="panel-body">
                                <div class="details-panel">
                                    <div class="item">
                                        <div class="form-group">
                                            <label for="carNumber" class="col-sm-2 control-label">联系人</label>
                                            <div class="col-sm-10">
                                                <input type="hidden" name="shipper.id" data-field="shipper-id">

                                                <div class="input-group">
                                                    <input type="text" name="shipper.name" data-field="shipper-name"
                                                           class="form-control"
                                                           placeholder="请输联系人姓名">
                                                    <span class="input-group-btn">
                                                    <button class="btn btn-default" type="button"
                                                            onclick="selectContact('shipper')">
                                                        <span class="glyphicon glyphicon-search"
                                                              aria-hidden="true"></span>
                                                    </button>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="item">
                                        <div class="form-group">
                                            <label for="carNumber" class="col-sm-2 control-label">联系电话</label>
                                            <div class="col-sm-10">
                                                <input type="text" name="shipper.tel" data-field="shipper-tel"
                                                       class="form-control" data-verification-type="mobile"
                                                       placeholder="请输入联系电话" required>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="item">
                                        <div class="form-group">
                                            <label for="carNumber" class="col-sm-2 control-label">所在地区</label>
                                            <div class="col-sm-10">
                                                <input type="text" name="shipper.zone" data-field="shipper-zone"
                                                       class="form-control"
                                                       placeholder="请输入所在地区" required>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="item">
                                        <div class="form-group">
                                            <label for="carNumber" class="col-sm-2 control-label">装货地点</label>
                                            <div class="col-sm-10">
                                                <input type="text" name="shipper.address" data-field="shipper-address"
                                                       class="form-control"
                                                       placeholder="装货地点" required>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="col-md-6">
                        <div class="panel panel-freight">
                            <div class="panel-heading"><b>收货方信息</b></div>
                            <div class="panel-body">
                                <div class="details-panel">
                                    <div class="item">
                                        <div class="form-group">
                                            <label for="carNumber" class="col-sm-2 control-label">联系人</label>
                                            <div class="col-sm-10">
                                                <div class="input-group">
                                                    <input type="hidden" name="receiver.id" data-field="receiver-id">
                                                    <input type="text" name="receiver.name" class="form-control"
                                                           placeholder="请输联系人姓名" data-field="receiver-name">
                                                    <span class="input-group-btn">
                                                    <button class="btn btn-default" type="button"
                                                            onclick="selectContact('receiver')">
                                                        <span class="glyphicon glyphicon-search"
                                                              aria-hidden="true"></span>
                                                    </button>
                                                    </span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <div class="item">
                                        <div class="form-group">
                                            <label for="carNumber" class="col-sm-2 control-label">联系电话</label>
                                            <div class="col-sm-10">
                                                <input type="text" name="receiver.tel" data-field="receiver-tel"
                                                       class="form-control" data-verification-type="mobile"
                                                       placeholder="请输入联系电话" required>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="item">
                                        <div class="form-group">
                                            <label for="carNumber" class="col-sm-2 control-label">所在地区</label>
                                            <div class="col-sm-10">
                                                <input type="text" name="receiver.zone" class="form-control"
                                                       data-field="receiver-zone"
                                                       placeholder="请输入所在地区" required>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="item">
                                        <div class="form-group">
                                            <label for="carNumber" class="col-sm-2 control-label">卸货地点</label>
                                            <div class="col-sm-10">
                                                <input type="text" name="receiver.address" class="form-control"
                                                       placeholder="请输入卸货地点" required data-field="receiver-address">
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <div class="panel panel-freight">
                            <div class="panel-heading"><b>货物详情</b></div>
                            <div class="panel-body">
                                <div class="details-panel">
                                    <div class="row">
                                        <div class="col-md-12">
                                            <div class="item">
                                                <div class="form-group">
                                                    <label for="carNumber" class="col-sm-1 control-label">承运要求</label>
                                                    <div class="col-sm-11">
                                                        <input type="text" class="form-control" name="claim"
                                                               placeholder="请输入承运要求" required>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-6">

                                            <div class="item">
                                                <div class="form-group">
                                                    <label for="carNumber" class="col-sm-2 control-label">约定路线</label>
                                                    <div class="col-sm-10">
                                                        <input type="text" class="form-control" name="appointedRoute"
                                                               placeholder="请输入约定路线" required>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="item">
                                                <div class="form-group">
                                                    <label for="carNumber" class="col-sm-2 control-label">公里数</label>
                                                    <div class="col-sm-10">
                                                        <input type="number" class="form-control" name="km" step="0.1"
                                                               placeholder="请输入公里数" min="0.0" required>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <div class="col-md-6">
                                            <div class="item">
                                                <div class="form-group">
                                                    <label for="carNumber" class="col-sm-2 control-label">运费</label>
                                                    <div class="col-sm-10">
                                                        <input type="number" class="form-control" name="cost" step="0.1"
                                                               placeholder="请输入运费" min="0.0" required>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="item">
                                                <div class="form-group">
                                                    <label for="carNumber" class="col-sm-2 control-label">装车重量</label>
                                                    <div class="col-sm-10">
                                                        <input type="number" class="form-control" name="weight"
                                                               step="0.1"
                                                               placeholder="请输入装车重量" min="0.0" required>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="row">
                                        <div class="col-md-12">
                                            <table id="table"></table>
                                        </div>
                                        <div class="col-md-12" style="margin-top: 10px;">
                                            <button type="button" class="btn btn-success btn-block"
                                                    onclick="openGoodsModal()">
                                                <span class="glyphicon glyphicon-check"></span>
                                                添加货物
                                            </button>
                                        </div>
                                        <#if Request.type=='DIRECT'>
                                            <div class="col-md-12" style="margin-top: 10px;">
                                                <table id="carDriverTable"></table>
                                            </div>

                                            <div class="col-md-12" style="margin-top: 10px;">
                                                <button type="button" class="btn btn-info btn-block"
                                                        onclick="openCarDriverModal()">
                                                    <span class="glyphicon glyphicon-check"></span>
                                                    指派车辆和司机
                                                </button>
                                            </div>
                                        </#if>

                                    </div>

                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </form>
</div>

<div class="modal fade" tabindex="-1" role="dialog" id="contactModal">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title">联系人信息</h4>
            </div>
            <div class="modal-body">
                <div class="search-bar">
                    <input type="text" placeholder="输入姓名回车查询" id="searchBox">
                </div>
                <table id="contactTable"></table>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="goodsModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="myModalLabel">货物</h4>
            </div>
            <div class="modal-body">
                <form id="goodsForm">
                    <div class="form-group">
                        <label for="displayName">品名</label>
                        <input type="text" class="form-control" name="displayName" placeholder="请输入货物名称">
                    </div>
                    <div class="form-group">
                        <label for="packages">包装</label>
                        <input type="text" class="form-control" name="packages" placeholder="请输入包装类型">
                    </div>
                    <div class="form-group" id="passwordDiv">
                        <label for="weights">重量/kg</label>
                        <input type="number" class="form-control" name="weights" placeholder="请输入货物重量">
                    </div>
                    <div class="form-group">
                        <label for="volume">体积/m³</label>
                        <input type="number" class="form-control" name="volume" placeholder="请输入货物体积">
                    </div>

                    <div class="form-group">
                        <label for="volume">体积/m³</label>
                        <input type="text" class="form-control" name="lwh" placeholder="请输入货物长宽高(例：1M*1M*1M)">
                    </div>
                    <div class="form-group">
                        <label for="quantity">数量/件</label>
                        <input type="number" class="form-control" name="quantity" placeholder="请输入货物数量">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="saveGoodsData()">保存</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="carDriverModal" tabindex="-1" role="dialog" aria-labelledby="carDriverModalLabel">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="carDriverModalLabel">车辆</h4>
            </div>
            <div class="modal-body">
                <form id="goodsForm">
                    <div class="form-group">
                        <label for="carSelect">车辆</label>
                        <select id="carSelect" class="selectpicker" title="请选择" name="type"
                                data-live-search="true"></select>
                    </div>

                    <div class="form-group">
                        <label for="driverSelect">司机</label>
                        <select id="driverSelect" class="selectpicker" title="请选择" name="type"
                                data-live-search="true"></select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="saveCarDriver()">保存</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="trailerModal" tabindex="-1" role="dialog" aria-labelledby="trailerModalLabel">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="trailerModalLabel">挂车</h4>
            </div>
            <div class="modal-body">
                <form id="goodsForm">
                    <div class="form-group">
                        <label for="trailerSelect">车牌号</label>
                        <select id="trailerSelect" class="selectpicker" title="请选择" name="trailer"
                                data-live-search="true"></select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="saveCarTrailer()">保存</button>
            </div>
        </div>
    </div>
</div>

</body>
</html>

<script type="text/javascript">
    var contactTable, addressType = 'shipper', goodsTable, carDriverTable;
    var id = 1;
    var carSelectDatas = [], driverSelectDatas = [];
    $(document).ready(function () {
        contactTable = $('#contactTable');
        contactTable.bootstrapTable({
            sidePagination: 'server',
            pagination: true,
            url: API_ADMIN_ADDRESS_BOOK + '/page',
            pageSize: 10,
            queryParamsType: '',
            ajaxOptions: {
                headers: {
                    access_token: getToken()
                }
            },
            responseHandler: function (res) {
                return {
                    "total": res.total,
                    "rows": res.list
                };
            },
            columns: [
                {field: 'id', title: 'ID', visible: false},
                {field: 'name', title: '联系人', width: 150},
                {field: 'tel', title: '联系电话', width: 150},
                {field: 'zone', title: '所在地区', width: 150},
                {field: 'address', title: '装货地点'},
                {
                    field: 'id', title: '操作', width: 80, align: 'center', formatter: function (value, row) {
                        return "<a href='javascript:chooseAddress(" + JSON.stringify(row) + ")'>选择</a>";
                    }
                }
            ]
        });

        $('#searchBox').keypress(function (event) {
            if (event.keyCode === 13) {
                if (event.keyCode === 13) {
                    if (event.keyCode === 13) {
                        var searchValue = $(this).val();
                        contactTable.bootstrapTable("refresh", {
                            query: {
                                name: searchValue
                            }
                        })

                    }
                }
            }
        });

        goodsTable = $('#table');
        goodsTable.bootstrapTable({
            pagination: false,
            columns: [
                {field: 'goodsId', title: 'ID', visible: false},
                {field: 'displayName', title: '品名'},
                {field: 'packages', title: '包装', width: 100, align: 'center'},
                {field: 'weights', title: '重量/kg', width: 100, align: 'center'},
                {field: 'volume', title: '体积/m³', width: 100, align: 'center'},
                {field: 'lwh', title: '长/宽/高', width: 200, align: 'center'},
                {field: 'quantity', title: '数量/件', width: 100, align: 'center'},
                {
                    field: 'goodsId', title: '操作', width: 100, align: 'center', formatter: function (value) {
                        return '<a href="javascript:removeGoods(' + value + ')">删除</a>';
                    }
                }
            ]
        });

        carDriverTable = $('#carDriverTable');
        carDriverTable.bootstrapTable({
            pagination: false,
            uniqueId: 'carId',
            columns: [
                {field: 'carId', title: 'ID', visible: false, width: 100},
                {field: 'driverId', visible: false},
                {field: 'driverName', title: '司机姓名', align: 'center'},
                {field: 'carNumber', title: '车牌号', width: 200, align: 'center'},
                {field: 'trailerNo', title: '挂车', width: 200, align: 'center'},
                {
                    field: 'id', title: '操作', width: 150, align: 'center', formatter: function (value, row) {
                        return '<a href="javascript:addTrailer(' + row.carId + ')">添加挂车</a>' +
                            ' | ' +
                            '<a href="javascript:removeCarDriver(' + row.carId + ')">移除</a>';
                    }
                }
            ]
        });

        var dataForm = $('#dataForm');
        dataForm.submit(function (data) {
            var target = data.target;
            var formData = {};

            var fieldInputs = $(target).find('input');
            for (var i = 0; i < fieldInputs.length; i++) {
                var item = fieldInputs[i];

                if ($(item).attr('data-verification-type') === 'mobile') {
                    if (checkPhone(item.value)) {
                        bootbox.alert('手机号码有误');
                        item.focus();
                        return false;
                    }
                }

                if (item.name && item.name !== '') {
                    var field = item.name;
                    if (field.indexOf('.') > -1) {
                        var child = field.split('.')[0];
                        var childField = field.split('.')[1];
                        if (!formData[child]) {
                            formData[child] = {};
                        }
                        formData[child][childField] = item.value;
                    } else {
                        formData[item.name] = item.value;
                    }
                }
            }
            formData['goodsDatas'] = goodsTable.bootstrapTable("getData");
            if (formData.type === 'DIRECT') {
                formData['carDriverIds'] = carDriverTable.bootstrapTable("getData");
            }

            $.httpclient.post(API_WAYBILL + "/one", JSON.stringify(formData), function (data) {
                location.href = ctx + '/admin/project';
            });

            return false;
        })

    });

    function selectContact(item) {
        addressType = item;
        $('#contactModal').modal('show')
    }

    function chooseAddress(data) {
        for (var item in data) {
            $('input[data-field=' + addressType + '-' + item + ']').val(data[item]);
        }
        $('#contactModal').modal('hide');
    }

    function openGoodsModal() {
        $('#goodsForm')[0].reset();
        $('#goodsModal').modal('show');
    }

    function saveGoodsData() {
        var form = $('#goodsForm');
        var formData = {};
        form.find('input').each(function () {
            formData[this.name] = this.value;
        });
        formData['goodsId'] = id;
        id++;
        goodsTable.bootstrapTable('append', formData);
        $('#goodsModal').modal('hide');
    }

    function removeGoods(id) {
        var ids = [];
        ids.push(id);
        goodsTable.bootstrapTable('remove', {
            field: 'goodsId',
            values: ids
        })
    }

    function openCarDriverModal() {
        var tableDatas = carDriverTable.bootstrapTable("getData");

        if (tableDatas.length > 0) {
            bootbox.alert('只能指派一个司机和车辆，如需选择其他司机，请移除已添加的司机');
            return false;
        }

        var carSelect = $('#carSelect');
        var driverSelect = $('#driverSelect');
        carSelect.empty();
        driverSelect.empty();

        $.httpclient.get(API_CAR + '/my', {
            time: new Date().getTime()
        }, function (data) {
            var datas = data.obj;
            carSelectDatas = datas;
            for (var i = 0; i < datas.length; i++) {
                var item = datas[i];
                var $option = $('<option></option>')
                $option.attr('value', item.id);
                $option.text(item.carNumber);
                carSelect.append($option);
            }
            carSelect.selectpicker('refresh');

            carSelect.on('changed.bs.select', function () {
                $.httpclient.get(API_CAR + '/driver', {
                    carId: this.value,
                    time: new Date().getTime()
                }, function (data) {
                    driverSelect.empty();
                    var datas = data.obj;
                    driverSelectDatas = datas;
                    for (var i = 0; i < datas.length; i++) {
                        var item = datas[i];
                        var $option = $('<option></option>')
                        $option.attr('value', item.id);
                        $option.text(item.realName);
                        driverSelect.append($option);
                    }
                    driverSelect.selectpicker('refresh');
                });
            });

            $('#carDriverModal').modal('show');
        });
    }

    function saveCarDriver() {
        var carSelect = $('#carSelect');
        var driverSelect = $('#driverSelect');
        var driveName, carNumber;
        var rowData = {};

        var carId = carSelect.val();
        if (!carId || carId === '') {
            bootbox.alert('请选择车辆');
            return;
        }
        carId = parseInt(carId);

        var tableDatas = carDriverTable.bootstrapTable("getData");
        for (var i = 0; i < tableDatas.length; i++) {
            var item = tableDatas[i];
            if (item.carId === carId) {
                bootbox.alert('请不要指定重复的车辆');
                return false;
            }
        }

        for (var i = 0; i < carSelectDatas.length; i++) {
            var item = carSelectDatas[i];
            if (item.id === carId) {
                rowData['carId'] = item.id;
                rowData['carNumber'] = item.carNumber;
                break;
            }
        }
        var driverId = driverSelect.val();
        if (!driverId || driverId === '') {
            bootbox.alert('请选择司机');
            return;
        }
        driverId = parseInt(driverId);
        for (var i = 0; i < driverSelectDatas.length; i++) {
            var item = driverSelectDatas[i];
            if (item.id === driverId) {
                rowData['driverId'] = item.id;
                rowData['driverName'] = item.realName;
                break;
            }
        }
        carDriverTable.bootstrapTable('insertRow', {
            index: 1,
            row: rowData
        });

        $('#carDriverModal').modal('hide');
    }

    function removeCarDriver(carId) {
        bootbox.confirm({
            size: "small",
            message: '是否移除车辆和司机?',
            buttons: {
                confirm: {
                    label: '是',
                    className: 'btn-danger'
                },
                cancel: {
                    label: '否',
                    className: 'btn-success'
                }
            },
            callback: function (result) {
                if (result) {
                    carDriverTable.bootstrapTable('remove', {field: 'carId', values: [carId]})
                }

            }
        });
    }

    var trailerCarId, trailerNo;

    function addTrailer(carId) {
        trailerCarId = carId;
        var trailerSelect = $('#trailerSelect');
        trailerSelect.empty();

        $.httpclient.get(API_CAR + '/my/trailer', {
            time: new Date().getTime()
        }, function (data) {
            var datas = data.obj;
            for (var i = 0; i < datas.length; i++) {
                var item = datas[i];
                var $option = $('<option></option>')
                $option.attr('value', item.id);
                $option.text(item.carNumber);
                trailerSelect.append($option);
            }
            trailerSelect.selectpicker('refresh');
        });
        $('#trailerModal').modal('show');
    }

    function saveCarTrailer() {
        var row = carDriverTable.bootstrapTable('getRowByUniqueId', trailerCarId);
        //carDriverTable.bootstrapTable('updateRow', {index: 1, row: row});
        // console.info(row);

        var trailerSelect = $('#trailerSelect');
        row['trailerNo'] = trailerSelect.find("option:selected").text();
        carDriverTable.bootstrapTable('updateRow', {index: 1, row: row});
        $('#trailerModal').modal('hide');
    }
</script>

